package com.iotproject.blogservice.controller.admin;

import com.iotproject.blogservice.entity.MyBlog;
import com.iotproject.blogservice.entity.vo.admin.ArticleQuery;
import com.iotproject.blogservice.service.MBlogService;
import com.iotproject.commonutils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("admin/blogservice/blog/")
public class AdminBlogController {

    @Autowired
    MBlogService blogService;

    @PostMapping("pageArticleCondition/{current}/{limit}")
    public R pageArticleCondition(@PathVariable("current") long current,
                                @PathVariable("limit") long limit,
                                @RequestBody(required = false) ArticleQuery articleQuery) {
        Page<MyBlog> blogPage = new Page<>(current, limit);
        QueryWrapper<MyBlog> blogQueryWrapper = new QueryWrapper<>();

        String userId = articleQuery.getUserId();
        String nickname = articleQuery.getNickname();
        String keyWords = articleQuery.getKeyWords();
        String articleType = articleQuery.getArticleType();
        String begin = articleQuery.getBegin();
        String end = articleQuery.getEnd();
        if (!StringUtils.isEmpty(keyWords)) {
            blogQueryWrapper.like("title", keyWords);
        }
        if (!StringUtils.isEmpty(nickname)) {
            blogQueryWrapper.like("nickname", nickname);
        }
        if (!StringUtils.isEmpty(userId)) {
            blogQueryWrapper.eq("user_id", userId);
        }
        if (!StringUtils.isEmpty(articleType)) {
            blogQueryWrapper.eq("blog_type", articleType);
        }
        if (!StringUtils.isEmpty(begin)) {
            blogQueryWrapper.ge("gmt_modified", begin);
        }
        if (!StringUtils.isEmpty(end)) {
            blogQueryWrapper.le("gmt_modified", end);
        }
        blogQueryWrapper.orderByDesc("gmt_modified");
        blogService.page(blogPage, blogQueryWrapper);
        long total = blogPage.getTotal();
        List<MyBlog> records = blogPage.getRecords();
        return R.ok().data("total", total).data("rows", records);
    }

    @DeleteMapping("deleteArticleById/{id}")
    public R deleteArticleById(@PathVariable("id") String id) {
        boolean removeById = blogService.removeById(id);
        if (removeById) {
            return R.ok();
        }
        return R.error();
    }

}
